﻿using System.Collections.Generic;
using System.Text.Json;

namespace DynamicChart.Service.Step.Format;

public class LegendStep : IFormatStep
{
    private readonly LoadService _loadService;
    
    public LegendStep(LoadService loadService)
    {
        _loadService = loadService;
    }
    
    public void Process(IDictionary<string, object> param, IDictionary<string, object> data)
    {
        var rawData = data["rawData"] as IDictionary<string, object>;
        var legend = new HashSet<string>();
        var legendTemp = new HashSet<string>();
        var configs = new Dictionary<string, object>();
        
        if (param.TryGetValue("id", out var id) && id != null)
        {
            configs = _loadService.GetSeriesConfig(int.Parse(id.ToString()));
        }

        foreach (var key in rawData.Keys)
        {
            if (rawData[key] is IDictionary<string, object> level2)
            {
                foreach (var level2Key in level2.Keys)
                {
                    Dictionary<string, object> config = null;
                    if (configs != null && configs.Count != 0)
                    {
                        config = JsonSerializer.Deserialize<Dictionary<string, object>>(
                            configs[level2Key].ToString()!)!;
                    }
                    
                    legend.Add(config != null ? config["name"].ToString() : level2Key);
                    legendTemp.Add(level2Key);
                }
            }
        }

        data["legend"] = legend;
        data["legendTemp"] = legendTemp;
    }
}